package org.apache.servicecomb.samples.practise.houserush.sale.dao;

import org.apache.servicecomb.samples.practise.houserush.sale.aggregate.HouseOrder;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.persistence.LockModeType;
import java.util.Date;
import java.util.List;

/**
 * @Author: Snake Man
 * @system:
 * @DateTime: 2022/1/18 13:16
 * @Description:
 */
public interface HouseOrderDao extends JpaRepository<HouseOrder,Integer> {

    //saleId-计算
    int countBySaleId(int saleId);

    //HouseId-查询
    HouseOrder findAllByHouseId(int houseId);;

    //cucustomerId-查询
    List<HouseOrder> findAllByCustomerId(int cucustomerId);

    @Modifying
    @Query(value ="UPDATE house_orders SET customer_id = ?1,state=?2,ordered_at=?3 where id = ?4 and customer_id is null ",nativeQuery = true)
    int updateByIdAndCustomerIdIsNull(int customerId, String state, Date orderedAt, int houseOrderId);

    //悲观锁定。其他事务不能同时读取或写入实体。
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT ho FROM HouseOrder ho WHERE ho.id = ?1")
    HouseOrder findOneForUpdate(int id);
}
